package com;

import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Iterator;

public class ExcelParser {

    private static final int STRING = 1;
    private static final int NUMERIC = 2;
    private static final int BOOLEAN = 3;

    public static void main(String[] args) throws IOException {
        String inputFilePath = "D:\\app\\aux表结构.xlsx";
        parseExcel(inputFilePath);

    }

    public static void parseExcel(String inputFilePath) throws IOException {
        FileInputStream fis = new FileInputStream(inputFilePath);
        Workbook workbook = new XSSFWorkbook(fis);
        Sheet sheet = workbook.getSheetAt(0);

        Iterator<Row> rowIterator = sheet.iterator();
        if (rowIterator.hasNext()) {
            Row headerRow = rowIterator.next();
            for (Cell cell : headerRow) {
                if (cell.getCellTypeEnum() == CellType.STRING) {
                    String tableName = cell.getStringCellValue();
                    if (!tableName.isEmpty()) {
                        writeTableDataToNewExcel(tableName, workbook);
                    } else {
                        System.out.println("表名不能为空");
                    }
                }
            }
        }

        fis.close();
    }

    private static void writeTableDataToNewExcel(String tableName, Workbook workbook) throws IOException {
        FileOutputStream fos = new FileOutputStream(tableName + ".xlsx");
        Workbook newWorkbook = new XSSFWorkbook();
        Sheet newSheet = newWorkbook.createSheet(tableName);

        // 假设原始表格的数据从第二行开始
        int startRowIndex = 1;
        int endRowIndex = workbook.getSheetAt(0).getLastRowNum();
        for (int i = startRowIndex; i <= endRowIndex; i++) {
            Row oldRow = workbook.getSheetAt(0).getRow(i);
            Row newRow = newSheet.createRow(i - startRowIndex);
            for (int j = 0; j < oldRow.getLastCellNum(); j++) {
                Cell oldCell = oldRow.getCell(j);
                Cell newCell = newRow.createCell(j);
                switch (oldCell.getCellType()) {
                    case STRING:
                        newCell.setCellValue(oldCell.getStringCellValue());
                        break;
                    case NUMERIC:
                        newCell.setCellValue(oldCell.getNumericCellValue());
                        break;
                    case BOOLEAN:
                        newCell.setCellValue(oldCell.getBooleanCellValue());
                        break;
                    default:
                        break;
                }
            }
        }

        newWorkbook.write(fos);
        fos.close();
        newWorkbook.close();
    }
}
